package mental_connect.backend.backend_ym.service;

import mental_connect.backend.backend_ym.entity.AccountInfo;
import mental_connect.backend.backend_ym.repository.AccountInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AccountInfoDetailService implements UserDetailsService {
    @Autowired
    private AccountInfoRepository accountInfoRepository;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AccountInfo account = accountInfoRepository.findByAccount(s);
        if (account == null) {
            throw new UsernameNotFoundException("Account not found with account: " + s);
        }
        List<GrantedAuthority> collect = account.getAuthority().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        return new AccountInfo(
                account.getId(),
                account.getAccount(),
                account.getPassword(),
                account.getAuthority(),
                collect
        );
    }
}
